package com.itsu.spbspider.service.impl;

import com.alibaba.fastjson.JSON;
import com.itsu.spbspider.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import ognl.Ognl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author suben
 * @create time 2020/2/10 20:18
 */
@Service
@Slf4j
public class BaiduWeatherParse {

    public Map parseObj(String content) throws SystemException {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        Map result = null;
        try {
            result = new HashMap();
            Map ret = JSON.parseObject(content);
            String errno = Ognl.getValue("errno", ret).toString();
            if (!"0".equals(errno)) {
                log.info("没有成功获取到天气数据");
                return null;
            }
            List weatherListSource = (List) Ognl.getValue("data.weather", ret);
            if (CollectionUtils.isEmpty(weatherListSource)) {
                return null;
            }
            List weatherList = new ArrayList();
            for (Object weatherObj : weatherListSource) {
                String time = BeanUtils.getProperty(weatherObj, "time");
                String weather = BeanUtils.getProperty(weatherObj, "weather");
                String temperature = BeanUtils.getProperty(weatherObj, "temperature");
                String date = BeanUtils.getProperty(weatherObj, "date");
                Map obj = new HashMap();
                obj.put("time", time);
                obj.put("weather", weather);
                obj.put("temperature", temperature);
                obj.put("date", date);
                weatherList.add(obj);
            }
            String image = Ognl.getValue("data.image", ret).toString();
            String nightimage = Ognl.getValue("data.nightimage", ret).toString();
            result.put("weatherList", weatherList);
            result.put("image", image);
            result.put("nightimage", nightimage);
        } catch (Exception e) {
            throw new SystemException(e);
        }

        return result;
    }
}
